import { defineConfig, loadEnv } from "vite";
import vue from "@vitejs/plugin-vue";
import { resolve } from "path";

import AutoImport from "unplugin-auto-import/vite";
import Components from "unplugin-vue-components/vite";
import { ElementPlusResolver } from "unplugin-vue-components/resolvers";

import {
  getPageEntries,
  dynamicGetAllPageEntries,
  htmlSize,
  adapterScript
} from "./vite.utils";

/**
 * 添加更多页面名称,这种方式的目的就是为了实现增量打包，可动态添加页面模块
 */
///const pages: string[] = ["home", "about", "login", "testhttp"];
const pages: string[] = ["order"];

const pageEntries11 = getPageEntries(pages);

const pageEntries1 = dynamicGetAllPageEntries();

console.log("pageEntries11=", pageEntries11);

/**
 * html 字符串处理插件
 * @param mode
 * @returns
 */
const htmlPlugins = (mode: string) => {
  return {
    name: "html-transform",
    transformIndexHtml(html: string) {
      // 加载环境变量
      const env = loadEnv(mode, process.cwd(), "");
      const scriptReg = /(<script (.*)><\/script>)/gi;

      const linkReg =
        /(<link\s+rel="([^"]+)"\s+crossorigin\s+href="([^"]+)">)/gi;

      const cssMatched = html.match(linkReg);

      //先拿到html中的所有的script标签
      let matched: string[] = html.match(scriptReg) || [];

      /**
       * 开发环境vite会自动注入<script type="module" src="/@vite/client"></script>，要过滤掉
       */
      if (env.VITE_APP_ENV === "development") {
        matched = matched.filter(
          (item) =>
            item !== '<script type="module" src="/@vite/client"></script>'
        );
      }

      return (
        html
          //去除默认CSS的注入位置
          .replace(/<link (.*)\/?>/gi, "")
          .replace(
            "</head>",
            `${cssMatched != null ? cssMatched.reverse().join("\n") : ""}\n</head>`
          )

          // 把统一的htmlSize和页面适配脚本注入到html中
          .replace(/(<title>.*<\/title>)/gi, `$1${htmlSize}${adapterScript}`)

          // //去除默认JS的注入位置
          .replace(scriptReg, "")

          //将 JavaScript 插入到 body 的最后
          .replace("</body>", `${matched[0]}\n</body>`)
      );
    }
  };
};

export default defineConfig(({ mode }) => {
  return {
    plugins: [
      vue(),
      htmlPlugins(mode),
      AutoImport({
        // 动态导入Vue,pinia的相关api也导入进来 ，这样页面上就用再通过import vue from vue这种格式了
        imports: ["vue", "pinia"],

        // 去解析API，这个配置会自动生成auto-imports.d.ts文件
        resolvers: [ElementPlusResolver()],

        eslintrc: { enabled: false } //给eslint生产的配置，只需要一次
      }),
      Components({
        // 解析组件，
        resolvers: [ElementPlusResolver()],

        //让用户在以下目录自定义的组件可以在要使用的页面上可以自动加载，会自动生成components.d.ts这个文件
        // 所有的组件可以自动加载
        dirs: [
          "src/components",
          "src/layout/components",
          "src/pages/**/components"
        ]
      })
    ],
    server: {
      //在.env.development环境配置参数去取
      port: 3000,
      host: true
    },
    resolve: {
      alias: [
        {
          find: "@",
          replacement: resolve(__dirname, "src")
        }
      ]
    },

    build: {
      outDir: "webapp",
      emptyOutDir: false,
      rollupOptions: {
        input: pageEntries1,
        output: {
          entryFileNames: "script/[name]/[name].[hash].js",
          chunkFileNames: "script/[name]/[name].[hash].js",
          assetFileNames(assetInfo) {
            if (assetInfo.name?.endsWith(".css")) {
              return "css/[name]/[name].[hash].css";
            }
            return "assets/[name]-[hash].[ext]";
          }
        }
      }
    }
  };
});
